package com.newdjk.newdoctor.ui;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bilibili.boxing.model.entity.BaseMedia;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.newdjk.newdoctor.BasActivity;
import com.newdjk.newdoctor.MyApplication;
import com.newdjk.newdoctor.R;
import com.newdjk.newdoctor.entity.SuggesttionEntity;
import com.newdjk.newdoctor.entity.UploadImageEntity;
import com.newdjk.newdoctor.net.BaseComPleteObserver;
import com.newdjk.newdoctor.net.NetServices;
import com.newdjk.newdoctor.utils.Base64Util;
import com.newdjk.newdoctor.utils.DisplayUtil;
import com.newdjk.newdoctor.utils.GlideUtils;
import com.newdjk.newdoctor.utils.LogUtils;
import com.newdjk.newdoctor.utils.StrUtil;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.MultiImageUploadView;
import com.newdjk.newdoctor.view.RoundImageUploadView;
import com.newdjk.okhttp.entity.BaseEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


public class SuggestionActivity extends BasActivity {


    private static final String TAG = "SuggestionActivity";
    @BindView(R.id.tv_pic_number)
    TextView tvPicNumber;
    @BindView(R.id.mSuggestionContent)
    EditText mSuggestionContent;
    @BindView(R.id.mEmail)
    EditText mEmail;
    @BindView(R.id.upload_view)
    RoundImageUploadView uploadView;
    private List<String> mSavePicList = new ArrayList<>(); //上传的图片凭证的数据源
    private Gson mGson;
    private final int IMAGE_REQUEST_CODE = 2;

    @Override
    protected int initViewResId() {
        return R.layout.activity_suggestion;
    }

    @Override
    public boolean IsShowBackIcon() {
        return true;
    }

    @Override
    protected void initView() {


//        initGridView();
        setUploadView();

        setRightTvVisible(true);
        setRightTvText("保存");
    }

    @Override
    protected void onRightTvClick(View v) {
        commitContent();
    }

    private void setUploadView() {
        uploadView.setAddHandlerImage(R.mipmap.image_add);
        uploadView.setMax(6);
        uploadView.setNumCol(4);
        uploadView.setImgMargin(DisplayUtil.dp2px(this, 10));
        uploadView.setCloseHandlerImage(R.drawable.ic_delete_photo);
        uploadView.setOnImageChangeListener(new MultiImageUploadView.OnImageChangeListener() {
            @Override
            public void onImageChage(List<File> imgFiles, int maxSize) {
                tvPicNumber.setText(String.format("(%d/%d)", imgFiles.size(), maxSize));
            }
        });
        uploadView.setPadding(0, 0, 0, 0);
        uploadView.setAddClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSelectImage();
            }
        });

        uploadView.setOnDelPicListener(new MultiImageUploadView.OnDelPicListener() {
            @Override
            public void onDelPicListener(int pos) {
                mSavePicList.remove(pos);
            }
        });


    }

    private void startSelectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }


    /**
     * 提交意见反馈的内容
     */
    private void commitContent() {
        if (!StrUtil.isNotEmpty(mSuggestionContent, true)) {
            ToastUtil.setToast("请输入建议内容");
            return;
        }
        if (!StrUtil.isNotEmpty(mEmail, true)) {
            ToastUtil.setToast("请输入联系方式");
            return;
        }
        if (mSavePicList == null || mSavePicList.size() == 0) {
            ToastUtil.setToast("请上传图片");
            return;
        }

        loading(true);
        int mSourceId = MyApplication.LoginEntity.getUser().getDoctorId();
        String mSourceName = MyApplication.LoginEntity.getUser().getDoctorName();
        int mSourceType = MyApplication.LoginEntity.getUser().getDrType();
        SuggesttionEntity mSuggesttionEntity = new SuggesttionEntity();
        mSuggesttionEntity.setSourceId(mSourceId);
        mSuggesttionEntity.setSourceName(mSourceName);
        mSuggesttionEntity.setSourceType(mSourceType);
        mSuggesttionEntity.setContact(mEmail.getText().toString());
        mSuggesttionEntity.setAdvice(mSuggestionContent.getText().toString());
        mSuggesttionEntity.setImgPaths(mSavePicList);

        String json = mGson.toJson(mSuggesttionEntity);
        LogUtils.d(TAG, json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
        NetServices.Factory.getService().AddFeedBack(
                body
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver(SuggestionActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity t) throws Exception {
                        Log.d(TAG, t.getData().toString());
                        ToastUtil.setToast("提交成功");
                        finish();
                    }

                });

    }


    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        mGson = new Gson();
    }


    private void uploadPicture(final String path) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                compressImage(path, emitter);
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext" + s);
                uploadImge(s, path);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    private void uploadImge(String s, final String path) {

        NetServices.Factory.getService().UploadImage(
                s + ""
                , "3"
        ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseComPleteObserver<UploadImageEntity>(SuggestionActivity.this) {
                    @Override
                    protected void onSuccees(BaseEntity<UploadImageEntity> t) throws Exception {
                        Log.d(TAG, t.getData().toString());
                        mSavePicList.add(t.getData().getSavePath());
                        uploadView.addFile(new File(path));
                    }

                });

    }

    public void compressImage(String filePath, final ObservableEmitter<String> emitter) {
        File oldFile = new File(filePath);
        Log.d("图片压缩", "之前" + oldFile.length());
        Luban.with(SuggestionActivity.this)
                .load(filePath)
                .ignoreBy(100)
                .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {

                        Log.d("图片压缩", "之后" + file.length());
                        emitter.onNext(Base64Util.imageToBase64(file.getAbsolutePath()));


                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:
                    Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = SuggestionActivity.this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String path = cursor.getString(columnIndex);  //获取照片路径
                    uploadPicture(path);
                    break;
            }
        }

    }



    @Override
    protected String setTitle() {
        return "意见反馈";
    }
}
